package com.coldworks.coldjoke;

import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.coldworks.base.BaseFragment;
import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.base.manager.BasePrefManager;
import com.coldworks.base.manager.BaseStorageManager;
import com.coldworks.base.util.BaseCONST;
import com.coldworks.coldjoke.R;
import com.coldworks.coldjoke.activity.LoginActivity;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.manager.UserManager.UserStateSubject;
import com.coldworks.coldjoke.model.JokeModel;
import com.coldworks.coldjoke.task.JudgeTask;
import com.coldworks.coldjoke.task.AsyncImgLoader;
import com.coldworks.coldjoke.task.AsyncImgLoader.UrlImageCallback;
import com.coldworks.coldjoke.ui.PopWindowUtils;
import com.coldworks.coldjoke.ui.PopWindowUtils.OnItemSelected;
import com.coldworks.coldjoke.util.CONST;
import com.coldworks.coldjoke.util.NetworkUtil;
import com.coldworks.coldjoke.util.UrlUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class NavigationJudgeFragment extends BaseFragment implements Observer {

	private ImageButton goodBtn;
	private ImageButton badBtn;
	private ImageButton reportBtn;
	private ImageButton skipBtn;
	private TextView judgeContent;
	private ImageView judgeImage;
	private Button loginButton;
	private Button retryButton;
	private LinearLayout judgeNoJokes;
	private ProgressDialog progressDialog;
	private LinearLayout operationBar;
	private LinearLayout judgeMain;
	private ImageButton menuBtn;
	private OnMenuShowListener onMenuShowListener;
	private boolean isLogin = false;
	private JokeModel jokeModel;
	private String jokeId;
	private Handler handler, reportHandler;
	private JudgeTask judgeTask;
	private FetchJokeUnreleasedTask fetchJokeUnreleasedTask;
	private String[] reportContent = new String[] { "政治敏感内容", "色情低俗信息", "乱发广告",
			"其他" };

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			onMenuShowListener = (OnMenuShowListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement onMenuShowListener");
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		userStateSubject = UserManager.getInstance().getUserStateSubject();
		userStateSubject.addObserver(this);
		isLogin = userStateSubject.getUserState() == UserManager.LOGINED ? true
				: false;
		jokeModel = new JokeModel();
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case BaseCONST.OP.SUCC:
					log.info("success");
					break;
				case BaseCONST.OP.ERR_NET:
					log.info("error net");
					break;
				case BaseCONST.OP.FAIL:
					log.info("failed");
					break;
				default:
					break;
				}
			}

		};
		reportHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				switch (msg.what) {
				case BaseCONST.OP.SUCC:
					log.info("success");
					Toast.makeText(getActivity(), "举报成功！", Toast.LENGTH_SHORT)
							.show();
					fetchJokeUnreleasedTask();
					break;
				case BaseCONST.OP.ERR_NET:
					Toast.makeText(getActivity(), "网络错误，举报失败，稍后再试试嘛",
							Toast.LENGTH_SHORT).show();
					log.info("error net");
					break;
				case BaseCONST.OP.FAIL:
					Toast.makeText(getActivity(), "网络错误，举报失败，稍后再试试嘛",
							Toast.LENGTH_SHORT).show();
					log.info("failed");
					break;
				default:
					break;
				}
			}

		};
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View view = inflater.inflate(R.layout.navigation_judge, container,
				false);
		menuBtn = (ImageButton) view.findViewById(R.id.button_menu);
		goodBtn = (ImageButton) view.findViewById(R.id.button_good);
		badBtn = (ImageButton) view.findViewById(R.id.button_bad);
		reportBtn = (ImageButton) view.findViewById(R.id.button_report);
		skipBtn = (ImageButton) view.findViewById(R.id.button_skip);
		judgeMain = (LinearLayout) view.findViewById(R.id.judge_main);
		judgeContent = (TextView) view.findViewById(R.id.judge_content);
		judgeImage = (ImageView) view.findViewById(R.id.judge_image);
		loginButton = (Button) view.findViewById(R.id.button_login);
		retryButton = (Button) view.findViewById(R.id.button_retry);
		judgeNoJokes = (LinearLayout) view.findViewById(R.id.judge_no_jokes);
		operationBar = (LinearLayout) view
				.findViewById(R.id.operation_bar_judge);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		if (isLogin) {
			showloginView();
			fetchJokeUnreleasedTask();
		} else {
			showUnloginView();
		}

		retryButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				fetchJokeUnreleasedTask();
			}
		});

		loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onMenuShowListener.showMenuLogin();
			}
		});

		goodBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				judgeTask = new JudgeTask(getActivity(), handler, jokeId,
						"laugh", null);
				judgeTask.start();
				fetchJokeUnreleasedTask();
			}
		});
		badBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				judgeTask = new JudgeTask(getActivity(), handler, jokeId,
						"unlaugh", null);
				judgeTask.start();
				fetchJokeUnreleasedTask();
			}
		});
		reportBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (reportWindow.isShowing()) {
					reportWindow.dismiss();
				} else {
					reportWindow.showAtLocation(retryButton, Gravity.BOTTOM, 0,
							0);
				}
			}
		});
		skipBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				fetchJokeUnreleasedTask();
			}
		});

		menuBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onMenuShowListener.showMenuNavigation();
			}
		});

		reportWindow = PopWindowUtils.MenuReportView(getActivity(),
				new OnItemSelected() {

					@Override
					public void onClick(int itemID) {
						reportWindow.dismiss();
						switch (itemID) {
						case R.id.button_report_1:
							judgeTask = new JudgeTask(getActivity(),
									reportHandler, jokeId, "report",
									reportContent[1]);
							judgeTask.start();
							break;
						case R.id.button_report_2:
							judgeTask = new JudgeTask(getActivity(),
									reportHandler, jokeId, "report",
									reportContent[2]);
							judgeTask.start();
							break;
						case R.id.button_report_3:
							judgeTask = new JudgeTask(getActivity(),
									reportHandler, jokeId, "report",
									reportContent[3]);
							judgeTask.start();
							break;
						case R.id.button_report_4:
							judgeTask = new JudgeTask(getActivity(),
									reportHandler, jokeId, "report",
									reportContent[4]);
							judgeTask.start();
							break;
						case R.id.button_cancle:
							// reportWindow.dismiss();
							break;
						default:
							break;
						}

					}
				});

	}

	private PopupWindow reportWindow;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case CONST.RESULT.JUDGE_RESULT:
			if (resultCode == CONST.RESULT.RESULT_OK) {
				fetchJokeUnreleasedTask();
			} else if (resultCode == CONST.RESULT.RESULT_CANCELED) {
				// 保持现状
			} else {
				// 保持现状
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	public void fetchJokeUnreleasedTask() {
		fetchJokeUnreleasedTask = new FetchJokeUnreleasedTask(getActivity(),
				jokeModel);
		fetchJokeUnreleasedTask.execute();
	}

	class FetchJokeUnreleasedTask extends AsyncTask<Void, Void, Integer> {

		private Context context;

		public FetchJokeUnreleasedTask(Context context, JokeModel jokeInfo) {
			this.context = context;
		}

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage(context.getResources().getString(
					R.string.judge_getting));
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.setOnCancelListener(new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					FetchJokeUnreleasedTask.this.cancel(true);
				}
			});
			progressDialog.show();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			DefaultHttpClient httpclient;
			HttpGet get = new HttpGet(UrlUtil.getJudgeJokeUrl(getActivity()));
			httpclient = BaseNetworkManager.getInstance().createHttpClient(
					context);
			try {
				String sessionId = UserManager.getInstance().getSessionId();
				get.setHeader("COOKIE", "webpy_session_id=" + sessionId);
				HttpResponse response = httpclient.execute(get);
				if (isCancelled()) {
					log.info("cancelled");
					return BaseCONST.OP.CANCEL;
				}
				if (response.getStatusLine().getStatusCode() == 200) {
					Header contentEncoding = response
							.getFirstHeader("Content-Encoding");
					JSONObject jsonObject = null;
					if (contentEncoding != null
							&& contentEncoding.getValue().equalsIgnoreCase(
									"gzip")) {
						jsonObject = NetworkUtil.getInstance()
								.getJsonObjectByGzip(
										response.getEntity().getContent());
					} else {
						jsonObject = NetworkUtil.getInstance().getJSONObject(
								response.getEntity().getContent());
					}
					if (jsonObject == null) {
						return BaseCONST.OP.ERR_NET;
					}
					if (jsonObject.getString("success").equals("false")) {
						return BaseCONST.OP.NO_JOKES;
					}
					// 填充笑话内容用来展示
					jokeModel.setJokeId(jsonObject.getString("Jokeid"));
					jokeId = jsonObject.getString("Jokeid");
					jokeModel.setJokeText(jsonObject.getString("content"));
					jokeModel.setTime(jsonObject.getString("created"));
					String url = jsonObject.getString("uri");
					if (!url.equals("") && !url.startsWith("http")) {
						url = CONST.URL.HOST + url;
					}
					jokeModel.setImgUrl(url);
					BasePrefManager.getInstance().setStringToPrefs(
							getActivity(), CONST.VALUE.JOKE_ID, jokeId);
					return BaseCONST.OP.SUCC;
				} else {
					log.info(String.valueOf(response.getStatusLine()
							.getStatusCode()));
					return BaseCONST.OP.ERR_NET;
				}
			} catch (ClientProtocolException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			} catch (IOException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			} catch (JSONException e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			} catch (Exception e) {
				log.error("", e);
				return BaseCONST.OP.ERR_NET;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
			switch (result) {
			case BaseCONST.OP.SUCC:
				showJoke();
				log.info("succuss");
				break;
			case BaseCONST.OP.ERR_NET:
				Toast.makeText(context, R.string.err_connecting,
						Toast.LENGTH_LONG).show();
				showRetryView();
				break;
			case BaseCONST.OP.NO_JOKES:
				showNoJokesView();
				log.info("no jokes");
				break;
			case BaseCONST.OP.CANCEL:
				break;
			}
		}
	}

	public void showUnloginView() {
		judgeMain.setVisibility(View.GONE);
		loginButton.setVisibility(View.VISIBLE);
		judgeNoJokes.setVisibility(View.GONE);
		retryButton.setVisibility(View.GONE);
		operationBar.setVisibility(View.GONE);
	}

	public void showloginView() {
		judgeMain.setVisibility(View.VISIBLE);
		loginButton.setVisibility(View.GONE);
		judgeNoJokes.setVisibility(View.GONE);
		retryButton.setVisibility(View.GONE);
		operationBar.setVisibility(View.VISIBLE);
	}

	public void showNoJokesView() {
		judgeMain.setVisibility(View.GONE);
		loginButton.setVisibility(View.GONE);
		judgeNoJokes.setVisibility(View.VISIBLE);
		retryButton.setVisibility(View.GONE);
		operationBar.setVisibility(View.GONE);
	}

	public void showRetryView() {
		judgeMain.setVisibility(View.GONE);
		loginButton.setVisibility(View.GONE);
		judgeNoJokes.setVisibility(View.GONE);
		retryButton.setVisibility(View.VISIBLE);
		operationBar.setVisibility(View.VISIBLE);
	}

	private void showJoke() {
		final LayoutParams fillWidth = new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		final LayoutParams wrapWidth = new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		judgeContent.setText(jokeModel.getJokeText());
		judgeImage.setVisibility(View.GONE);
		final String url = jokeModel.getImgUrl();
		if (!url.equals("")) {
			judgeImage.setVisibility(View.VISIBLE);
			judgeImage.setLayoutParams(wrapWidth);
			judgeImage.setImageResource(R.drawable.ic_photo);
			Bitmap cachedImage = AsyncImgLoader.getInstance()
					.loadDrawableByUrl(
							getActivity(),
							url,
							judgeImage,
							new UrlImageCallback() {
								@Override
								public void imageLoaded(Bitmap imageDrawable,
										ImageView imageView, String imageUrl) {
									judgeImage.setLayoutParams(fillWidth);
									imageView.setImageBitmap(imageDrawable);
								}
							}, BaseStorageManager.getInstance().getImgDir(),
							false);
			if (cachedImage != null) {
				judgeImage.setLayoutParams(fillWidth);
				judgeImage.setImageBitmap(cachedImage);
			} else {
				judgeImage.setImageResource(R.drawable.ic_photo);
				judgeImage.setLayoutParams(wrapWidth);
			}
		}
	}

	private UserStateSubject userStateSubject;

	@Override
	public void update(Observable o, Object data) {
		UserStateSubject observable = (UserStateSubject) o;
		if (observable.getUserState() == UserManager.LOGINED) {
			isLogin = true;
			judgeMain.setVisibility(View.VISIBLE);
			loginButton.setVisibility(View.GONE);
			operationBar.setVisibility(View.VISIBLE);
			retryButton.setVisibility(View.GONE);
			fetchJokeUnreleasedTask();
			log.info("JudgeFragment已注册，并被通知到登陆状态");
		} else {
			isLogin = false;
			judgeMain.setVisibility(View.GONE);
			loginButton.setVisibility(View.VISIBLE);
			operationBar.setVisibility(View.GONE);
			retryButton.setVisibility(View.GONE);
			log.info("JudgeFragment已注册，并被通知到未登陆状态");
		}

	}
}
